package mapEditor.view
{
	import asset.mapEditor.assetItemAsset;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.utils.describeType;
	
	import mapEditor.common.DisplayObjectManager;
	import mapEditor.common.MapAssetManager;
	import mapEditor.model.EditorModel;
	import mapEditor.vo.ToolType;

	public class AssetClassItemView extends assetItemAsset
	{
		private var _model:EditorModel;
		private var _classType:String;
		private var _xmlItem:XML;
		private var _itemThumbnail:*;
		private var _thumbnailWidth:Number=42;
		private var _thumbnailHeight:Number=42;
		
		public function AssetClassItemView(model:EditorModel, xmlItem:XML)
		{
			_model=model;
			_xmlItem=xmlItem;
			buttonMode=true;
			loadItemThumbnail();
			
			addEventListener(MouseEvent.CLICK, __onClick);
			
			gotoAndStop(1);
		}
		
		private function __onClick(evt:MouseEvent):void
		{
			_model.assetName=_xmlItem.@name;
			_model.assetClassType=_classType;
			_model.assetLink=_xmlItem.@link;
			if(!_xmlItem.hasOwnProperty("@x") || !_xmlItem.hasOwnProperty("@y"))
			{
				_model.assetPoint=null;
			}
			else
			{
				_model.assetPoint=new Point();
				_model.assetPoint.x=Number(_xmlItem.@x);
				_model.assetPoint.y=Number(_xmlItem.@y);
			}
			_model.toolType=ToolType.MAP_ADD_ASSET;
			_model.mouseAssetLink=_xmlItem.@link;
			
			gotoAndStop(2);
		}
		
		private function loadItemThumbnail():void
		{
			if(!_xmlItem) return;
			
			_itemThumbnail=MapAssetManager.getAssetByType(_xmlItem.@link);
			if(!_itemThumbnail) return;

			_classType=describeType(_itemThumbnail).@base;
			switch(_classType)
			{
				case "flash.display::BitmapData":
					thumbnailShow(new Bitmap(_itemThumbnail as BitmapData));
					break;
				case "flash.display::MovieClip":
					thumbnailShow(_itemThumbnail as MovieClip);
					break;
			}
			_itemThumbnail=null;
		}
		
		private function thumbnailShow(dis:DisplayObject):void
		{
			DisplayObjectManager.thumbnailShow(dis, _thumbnailWidth, _thumbnailHeight);
			addChild(dis);
		}
		
		public function dispose():void
		{
			_model=null;
			_xmlItem=null;
			
			if(_itemThumbnail as BitmapData) (_itemThumbnail as BitmapData).dispose();
			_itemThumbnail=null;
			if(parent) parent.removeChild(this);
		}
	}
}